package com.smartens.boit.activity;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.configure.PickerOptions;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.smartens.boit.R;
import com.smartens.boit.base.BaseActivity;
import com.smartens.boit.bean.ElectricBean;
import com.smartens.boit.bean.EnergyConsumptionBean;
import com.smartens.boit.bean.StatusDetailBean;
import com.smartens.boit.util.HttpHelper;
import com.smartens.boit.util.LineChartUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;


/**
 * @Description 能耗详情
 * @Author songtt
 * @Date 2021/3/4
 */
public class EnergyDetailActivity extends BaseActivity {
    private static final String TAG = "EnergyDetailActivity";
    private LinearLayout back;
    private LinearLayout linearLayout1;
    private LinearLayout linearLayout2;
    private LinearLayout linearLayout3;
    private RadioButton radioButton1;
    private RadioButton radioButton2;
    private RadioButton radioButton3;
    private TextView DevicesNum;
    private TextView DevicesName;
    private TextView TotalPower;
    private TextView CurrentVoltage1;
    private TextView CurrentElectric1;
    private TextView tvPower;
    private TextView tvChooseDateTime;


    /**
     * 能耗
     */
    private BarChart barChart;
    private YAxis leftAxis;
    private YAxis rightAxis;
    private XAxis xAxis;
    private Legend legend;


    private List<Integer> listData = new ArrayList<>();
    private List<Integer> listData2 = new ArrayList<>();
    private List<String> xValues = new ArrayList<>();
    private List<String> yValues = new ArrayList<>();

    /**
     * 请求 helper
     */
    private HttpHelper helper;

    /**
     * 电压 list
     */
    private ArrayList<Entry> listV1 = new ArrayList<>();
    private ArrayList<Entry> listV2 = new ArrayList<>();
    private ArrayList<Entry> listV3 = new ArrayList<>();

    /**
     * 电流 list
     */
    private ArrayList<Entry> listE1 = new ArrayList<>();
    private ArrayList<Entry> listE2 = new ArrayList<>();
    private TextView time1;
    private TextView time2;
    private ArrayList<Entry> listE3 = new ArrayList<>();

    /**
     * 电压 电流 chart
     */
    private LineChart vChart, cChart;

    /**
     * 日期数据
     */
    ArrayList<String> timeList = new ArrayList<String>();
    private ScheduledExecutorService mUpdateTime;
    private TimerTask mUpdateTask;
    Handler handler = new Handler();
    private Float currentValue;
    private Date currentDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_energy_detail);
        time1 = findViewById(R.id.timeone);
        time2 = findViewById(R.id.timetwo);
        back = findViewById(R.id.tv_back);
        tvChooseDateTime = findViewById(R.id.tvChooseDateTime);
        linearLayout1 = findViewById(R.id.lin_01);
        linearLayout2 = findViewById(R.id.lin_02);
        linearLayout3 = findViewById(R.id.lin_03);
        radioButton1 = findViewById(R.id.rb_01);
        radioButton2 = findViewById(R.id.rb_02);
        radioButton3 = findViewById(R.id.rb_03);
        CurrentElectric1 = findViewById(R.id.CurrentElectric1);
        CurrentVoltage1 = findViewById(R.id.CurrentVoltage1);
        TotalPower = findViewById(R.id.TotalPower);
        DevicesNum = findViewById(R.id.DevicesNum);
        DevicesName = findViewById(R.id.DevicesName);
        tvPower = findViewById(R.id.tv_power);
        radioButton1.setChecked(true);
        linearLayout1.setVisibility(View.VISIBLE);
        linearLayout2.setVisibility(View.GONE);

//        能耗
        barChart = findViewById(R.id.chart);
        for (int i = 1; i < 10; i++) {
            listData.add(i + 10);
            listData2.add(i + 15);

        }

        // 请求
        helper = HttpHelper.getInstance();

        handler.postDelayed(runnable, 0);
//        能耗
        getDeviceEneygyList();
        // 获取设备状态信息
        GetDeviceStatusListResult();
        radioButton1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                linearLayout1.setVisibility(View.VISIBLE);
                linearLayout2.setVisibility(View.GONE);
                linearLayout3.setVisibility(View.GONE);
            }
        });
        radioButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                linearLayout1.setVisibility(View.GONE);
                linearLayout2.setVisibility(View.VISIBLE);
                linearLayout3.setVisibility(View.GONE);
            }
        });
        radioButton3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                linearLayout1.setVisibility(View.GONE);
                linearLayout2.setVisibility(View.GONE);
                linearLayout3.setVisibility(View.VISIBLE);
            }
        });

        tvChooseDateTime.setOnClickListener(v -> {
            initTimePickerView();
        });

        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EnergyDetailActivity.this.finish();
            }
        });

    }


    private void initTimePickerView() {
        TimePickerBuilder builder = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                currentDate = date;
                getDeviceStatusHistoryList();
            }
        });
        builder.setType(new boolean[]{true, true, true, true, false, false})
                .setRangDate(null,Calendar.getInstance())
                .setCancelText("取消").setCancelColor(Color.RED)
                .setTitleText("选择日期时间").setTitleColor(Color.parseColor("#333333"))
                .setSubmitText("确认").setSubmitColor(Color.parseColor("#557e42"))
                .build().show();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            Log.d(TAG, "run: ===获取电压 电流数据");
            getDeviceStatusHistoryList();
            handler.postDelayed(this, 10000);
        }
    };

    private void startUpdateTimer() {
        if (mUpdateTime == null) {
            mUpdateTime = new ScheduledThreadPoolExecutor(2, new ThreadFactory() {
                @Override
                public Thread newThread(Runnable runnable) {
                    Thread thread = Executors.defaultThreadFactory().newThread(runnable);
                    thread.setName(EnergyDetailActivity.class.getSimpleName());
                    return thread;
                }
            });
            mUpdateTask = new TimerTask() {
                @Override
                public void run() {
                    // 获取电压 电流数据
                    Log.d(TAG, "run: ===获取电压 电流数据");
                    getDeviceStatusHistoryList();
                }
            };
        }
        mUpdateTime.scheduleWithFixedDelay(mUpdateTask, 0, 10, TimeUnit.SECONDS);
    }


    /**
     * getDeviceStatusHistoryList 获取电压 电流数据
     */
    private void getDeviceStatusHistoryList() {
        // 获取当时日期 时间
        if (currentDate == null) {
            long time = System.currentTimeMillis();
            currentDate = new Date(time);
        }
        // 日期-参数格式2021-05-13 15:00
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd H:00");
        //参数
        String timeSpan = dateFormat.format(currentDate);
        Log.d(TAG, "getDeviceStatusHistoryList: " + currentDate);
        time1.setText("更新时间 " + dateFormat.format(currentDate));
        time2.setText("更新时间 " + dateFormat.format(currentDate));

        // 调接口
        helper.GetDeviceStatusHistoryList(timeSpan, new HttpHelper.HttpCallBack<ElectricBean>() {
            @Override
            public void onSuccess(List<ElectricBean> result) {
                // init 电流电压折线图

                EnergyDetailActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //   Log.v(TAG, "刷新页面！");
                        listE1.clear();
                        listV1.clear();
                        timeList.clear();
                        initCurrentChart(result);
                    }

                });
                Log.v("GetDeviceStatus", result.toString());
            }

            @Override
            public void onFailure(String message) {
                // Log.v("====电流电压 请求失败", message);
                // 电压
                vChart =  findViewById(R.id.chart_voltage);
                // 电流
                cChart =  findViewById(R.id.chart_current);
                cChart.clear();
                vChart.clear();
                vChart.setNoDataText("暂无数据");
                cChart.setNoDataText("暂无数据");
            }
        });
    }

    /**
     * 电压 电流 折线图
     *
     * @param result 返回数据
     */
    private void initCurrentChart(List<ElectricBean> result) {
        // 电压
        this.vChart = (LineChart) findViewById(R.id.chart_voltage);

        // 电流
        this.cChart = (LineChart) findViewById(R.id.chart_current);

        // 循环 赋值
        for (int i = 0; i < result.size(); i++) {
            // 电压值 —— String类型 无法直接使用
            String v1 = result.get(i).getCurrentVoltage1();
            String v2 = result.get(i).getCurrentVoltage2();
            String v3 = result.get(i).getCurrentVoltage3();

            // 电流值 —— String类型 无法直接使用
            String e1 = result.get(i).getCurrentElectric1();
            String e2 = result.get(i).getCurrentElectric2();
            String e3 = result.get(i).getCurrentElectric3();


            //电压line  赋值
            addLineData(listV1, v1, i);
            addLineData(listV2, v2, i);
            addLineData(listV3, v3, i);

            //电流 line  赋值
            addLineData(listE1, e1, i);
            addLineData(listE2, e2, i);
            addLineData(listE3, e3, i);

            // 赋值 时间 —— X 轴
            String timeVal = String.valueOf(result.get(i).getUpdateTime().split(" ")[1]);
            timeList.add(timeVal);
        }
        Log.d(TAG, "initCurrentChart: listE1= " + listE1);
        //电压 折线图
        new LineChartUtils(this, listV1, listV2, listV3, timeList, vChart, 0f, 250f, 50f);
        vChart.postInvalidate();
        cChart.invalidate();
        //电流 折线图
        new LineChartUtils(this, listE1, listE2, listE3, timeList, cChart, 0f, 0, 0f);
//        cChart.setVisibility(View.VISIBLE);
        cChart.postInvalidate();
        cChart.invalidate();
    }


    /**
     * setLineList 设置line的数据
     *
     * @param list  要进行添加值的list
     * @param value 赋的值
     * @param i
     */
    private void addLineData(ArrayList<Entry> list, String value, int i) {
        //判 非空  赋值
        if (!TextUtils.isEmpty(value)) {
            // 将 字符串值转为float
            Float currentValue = Float.parseFloat(value);
            list.add(new Entry(i, (float) currentValue));
        }
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    /**
     * 初始化BarChart图表
     */
    private void initBarChart(BarChart barChart) {
        /***图表设置***/
        //背景颜色
        barChart.setBackgroundColor(Color.WHITE);
        //不显示图表网格
        barChart.setDrawGridBackground(false);
        //背景阴影
        barChart.setDrawBarShadow(false);
        barChart.setHighlightFullBarEnabled(false);
        //显示边框
        barChart.setDrawBorders(false);

        //不显示右下角描述内容
        Description description = new Description();
        description.setEnabled(false);
        barChart.setDescription(description);
        /***XY轴的设置***/
        //X轴设置显示位置在底部
        xAxis = barChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setAxisMinimum(0f);
        xAxis.setGranularity(1f);
        //X轴横坐标显示的数量
        xAxis.setLabelCount(18);
        // 不显示X轴 Y轴线条
        xAxis.setDrawAxisLine(false);
        xAxis.setDrawGridLines(false);
        leftAxis = barChart.getAxisLeft();
        rightAxis = barChart.getAxisRight();

        //保证Y轴从0开始，不然会上移一点
        leftAxis.setAxisMinimum(0f);
        rightAxis.setAxisMinimum(0f);

        //右侧Y轴网格线设置为虚线
        YAxis yAxis = barChart.getAxisLeft();
        yAxis.setLabelCount(6);
        yAxis.enableGridDashedLine(10f, 10f, 0f);
        // 设置x轴轴线的宽度
        xAxis.setAxisLineWidth(1);
        // 设置轴线的颜色
        xAxis.setAxisLineColor(Color.parseColor("#A4A4A4"));
        // 设置坐标颜色
        xAxis.setTextColor(Color.parseColor("#A4A4A4"));
        // 去掉右侧 的坐标轴
        barChart.getAxisRight().setEnabled(false);
        // 设置轴线的颜色
        yAxis.setAxisLineColor(Color.parseColor("#A4A4A4"));
        // 设置坐标颜色
        yAxis.setTextColor(Color.parseColor("#A4A4A4"));
        // 柱子宽度  ？？？？？
        barChart.setVisibleXRangeMaximum(8);
        barChart.setDoubleTapToZoomEnabled(false);
        //禁止拖拽
        barChart.setDragEnabled(false);
        //X轴或Y轴禁止缩放
        barChart.setScaleXEnabled(false);
        barChart.setScaleYEnabled(false);
        barChart.setScaleEnabled(false);
        //禁止所有事件
        barChart.setTouchEnabled(false);

        /***折线图例 标签 设置***/
        legend = barChart.getLegend();
        legend.setForm(Legend.LegendForm.LINE);
        legend.setTextSize(0f);

        //显示位置

        legend.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        legend.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        legend.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        //是否绘制在图表里面
        legend.setDrawInside(false);
        showBarChart(yValues, "", getResources().getColor(R.color.white));
    }


    /**
     * 柱状图始化设置 一个BarDataSet 代表一列柱状图
     *
     * @param barDataSet 柱状图
     * @param color      柱状图颜色
     */
    private void initBarDataSet(BarDataSet barDataSet, int color) {
        barDataSet.setColor(color);
        barDataSet.setFormLineWidth(0f);
        barDataSet.setFormSize(0f);
        //不显示柱状图顶部值
        //设置柱形的颜色
        barDataSet.setColor(getResources().getColor(R.color.myblue));
        barDataSet.setDrawValues(false);

    }

    public void showBarChart(List<String> dateValueList, String name, int color) {
        ArrayList<BarEntry> entries = new ArrayList<>();
        for (int i = 0; i < dateValueList.size(); i++) {
            /**
             * 此处还可传入Drawable对象 BarEntry(float x, float y, Drawable icon)
             * 即可设置柱状图顶部的 icon展示
             */
            BarEntry barEntry = new BarEntry(i, Float.parseFloat(dateValueList.get(i)));
            entries.add(barEntry);
        }
        //每一个BarDataSet代表一类柱状图
        BarDataSet barDataSet = new BarDataSet(entries, name);
        initBarDataSet(barDataSet, color);
        //X轴自定义值
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int index = (int) value;
             /*   if (index >= 0 && index < 16) {
                    return xValues.get(index);
                } else {
                    return "";
                }*/
                if (!(index%5==0))
                {
                    return "";
                }
                else
                    {
                        return xValues.get(index);
                    }
            }
        });

        BarData data = new BarData(barDataSet);
        barChart.setData(data);
    }

    public void GetDeviceStatusListResult() {
        helper.GetDeviceStatusListResult(new HttpHelper.HttpCallBack<StatusDetailBean>() {

            @SuppressLint("LongLogTag")

            @Override
            public void onSuccess(List<StatusDetailBean> result) {
                if (result.size() > 0) {
                    Log.d(TAG, "onSuccess: GetDeviceStatusListResult" + result.get(0));
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            DevicesName.setText(result.get(0).getDevicesName());
                            DevicesNum.setText("设备编号 " + result.get(0).getDevicesNum());
                            TotalPower.setText(result.get(0).getTotalPower());
                            CurrentVoltage1.setText(result.get(0).getCurrentVoltage1());
                            CurrentElectric1.setText(result.get(0).getCurrentElectric1());
                            tvPower.setText(result.get(0).getTotalPower());
                        }
                    });
                } else {
                    Log.d(TAG, "onSuccess: GetDeviceStatusListResult" + 0);

                }


            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                //  Log.v(TAG, "GetDeviceStatusList" + message);
            }
        });
    }

    public void getDeviceEneygyList() {
        helper.GetDeviceEneygyList(new HttpHelper.HttpCallBack<EnergyConsumptionBean>() {

            @SuppressLint("LongLogTag")
            @Override
            public void onSuccess(List<EnergyConsumptionBean> result) {
                Log.d(TAG, "onSuccess:getDeviceEneygyList" + result.size());

                xValues.clear();
                yValues.clear();
                for (int i = 0; i < result.size(); i++) {
                    result.get(i).getTotalTime();
                    result.get(i).getTotalEnergy();
                    xValues.add(result.get(i).getTotalTime().substring(5));
                    yValues.add(result.get(i).getTotalEnergy());
                }

                //  Log.v("TAG", "onSuccess: " + xValues);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initBarChart(barChart);
                    }
                });
            }

            @SuppressLint("LongLogTag")
            @Override
            public void onFailure(final String message) {
                //   Log.v(TAG, "onFailure: GetDeviceEneygyList" + message);
                barChart.setNoDataText("暂无数据");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) {
            handler.removeCallbacks(runnable);
        }
    }

}